# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'xin301214184366': {
        #  志成支付  支付宝 3% 200-10000 dwc
        'API_KEY': '6MXHOCGCCIEGO7TBU2OHAY5GFDU4BJTI',
        'gateway': 'https://inapi.xinpay.me/customer.pay',
        'query_gateway': 'https://inapi.xinpay.me/customer.Pay.query',
    },
    'xin100315199002': {
        #  志成支付  微信个码 4% 200-10000 dwc
        'API_KEY': 'VP0EFUPMAQT22LWUQ9NVBIF4YD4FW1IP',
        'gateway': 'https://inapi.xinpay.me/customer.pay',
        'query_gateway': 'https://inapi.xinpay.me/customer.Pay.query',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_rsp_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and k != 'sign_type':
            s += '%s=%s&' % (k, parameter[k])
    s += '%s' % key
    return generate_sign(s)


def gen_order_sign(d, key):
    s = 'ServerUrl={}&amount={}&backurl={}&businessnumber={}&failUrl={}&goodsName={}&mer_id={}&terminal={' \
        '}&timestamp={}&version={}&{}'.format(
        d['ServerUrl'], d['amount'], d['backurl'], d['businessnumber'], d['failUrl'], d['goodsName'],
        d['mer_id'], d['terminal'], d['timestamp'], d['version'], key
    )
    return generate_sign(s)


def gen_query_sign(d, key):
    s = 'businessnumber={}&mer_id={}&terminal={}&timestamp={}&version={}&{}'.format(
        d['businessnumber'], d['mer_id'], d['terminal'], d['timestamp'], d['version'], key
    )
    return generate_sign(s)


def gen_query_rsp_sign(d, key):
    s = '{}{}{}{}{}{}'.format(
        d['businessnumber'], d['mer_id'], d['terminal'], d['timestamp'], d['version'], key
    )
    return generate_sign(s)


def verify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_rsp_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("zhichengpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)
    else:
        return True


def _get_pay_type(service):
    # PC	对应网关支付
    # H5	对应快捷支付
    # ALI_CODE 支付宝扫码
    # ALI_PAY_WAP 支付宝H5支付
    # WEIXIN_PAY_WAP 微信H5支付
    # WEIXIN_PAY_SCAN 微信扫码支付
    # WEIXIN_CODE 微信个码支付
    if service == 'alipay_wap':
        return 'ALI_PAY_WAP'
    elif service == 'alipay_scan':
        return 'ALI_CODE'
    elif service == 'wechat_h5':
        return 'WEIXIN_PAY_WAP'
    elif service == 'wechat_scan':
        return 'WEIXIN_PAY_SCAN'
    elif service == 'wechat_single':
        return 'WEIXIN_CODE'
    elif service == 'alipay2card':
        return 'H5'
    return 'ALI_PAY_WAP'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mer_id', app_id),
        ('timestamp', local_now().strftime("%Y-%m-%d %H:%M:%S")),
        ('terminal', _get_pay_type(service)),
        ('version', '01'),
        ('amount', str(int(pay_amount * 100))),
        ('backurl', '{}/pay/api/{}/zhichengpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, app_id)),
        ('failUrl', '1'),
        ('ServerUrl', '{}/pay/api/{}/zhichengpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('businessnumber', str(pay.id)),
        ('goodsName', 'charge'),
        ('sign_type', 'md5'),
    ))
    parameter_dict['sign'] = gen_order_sign(parameter_dict, api_key)
    _LOGGER.info("zhichengpay create: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['businessnumber'])
    extend = json.loads(pay.extend or '{}')
    extend.update({'terminal': parameter_dict['terminal']})
    order_db.fill_extend(pay.id, extend)
    if service in ['alipay_wap', 'alipay_scan', 'wechat_h5', 'wechat_scan', 'wechat_single', 'alipay2card']:
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
        _LOGGER.info("zhichengpay create charge data: %s %s", response.status_code, response.text)
        return {'charge_info': json.loads(response.text)['data']['trade_qrcode']}
    else:
        html_text = _build_form(parameter_dict, _get_gateway(app_id))
        cache_id = redis_cache.save_html(pay.id, html_text)
        _LOGGER.info('zhichengpay url: %s', settings.PAY_CACHE_URL + cache_id)
        return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("zhichengpay notify data: %s, order_id is: %s", data, data['businessnumber'])
    verify_sign(data, api_key)
    pay_id = data['businessnumber']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('zhichengpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = unicode(data['status'])
    trade_no = ''
    total_fee = float(data['amount']) / 100.0
    terminal = json.loads(pay.extend or '{}').get('terminal', 0)
    extend = {
        'terminal': terminal,
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 校验成功
    if trade_status == u'成功':
        _LOGGER.info('zhichengpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    terminal = json.loads(pay_order.extend or '{}').get('terminal', 0)
    parameter_dict = OrderedDict((
        ('mer_id', app_id),
        ('timestamp', local_now().strftime("%Y-%m-%d %H:%M:%S")),
        ('terminal', terminal),
        ('version', '01'),
        ('businessnumber', str(pay_id)),
        ('sign_type', 'md5'),
    ))
    parameter_dict['sign'] = gen_query_sign(parameter_dict, api_key)
    _LOGGER.info("zhichengpay query data: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['businessnumber'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("zhichengpay query rsp data: %s", response.text)
    verify_sign(json.loads(response.text)['data'], api_key)
    if response.status_code == 200:
        data = json.loads(response.text)['data']
        trade_status = unicode(data['status'])
        trade_no = ''
        total_fee = float(data['amount']) / 100.0
        extend = {
            'terminal': terminal,
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 成功/处理中/失败
        if trade_status == u'成功':
            _LOGGER.info('zhichengpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('zhichengpay data error, status_code: %s', response.status_code)
